package com.quick.mail;

import com.quick.domain.Mail;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName MailServiceImpl
 * @Description 邮件发送
 * @Author Wangxin
 * @Date 2019-03-02 20:46
 * @Version 1.0
 **/
@Service
public class MailService {
    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private Configuration configuration;

    @Value("${spring.mail.username}")
    private String send;
    
    /**
     * @Author Wangxin
     * @Description 不使用模板发送邮件
     * @Date 21:21 2019-03-02
     * @Param [to, subject, content]
     * @return void
     **/
    public void sendMail(String to,String subject,String content) throws Exception{
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(send);
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(content);
        javaMailSender.send(simpleMailMessage);
    }
    
   /**
    * @Author Wangxin
    * @Description 使用模板发送
    * @Date 21:24 2019-03-02
    * @Param [mail, emailMsg]
    * @return void
    **/
    public void sendFreemarker(Mail mail)throws Exception{
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg,true);
        helper.setFrom(send);
        helper.setTo(mail.getTo());
        helper.setSubject(mail.getSubject());
        Map<String,Object> map = new HashMap<>();
        map.put("mail", mail);
        Template template = configuration.getTemplate(mail.getTemplate());
        String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        helper.setText(text, true);
        javaMailSender.send(msg);
    }
}
